import React, { useEffect, useState, useRef } from "react";
import { Modal, message, Space } from "antd";
import { hiprint } from "vue-plugin-hiprint";
import PrintModal from "./component/PrintModal";
import { SearchCheckboxTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import AddWarehouseOrderModal from "./component/AddWarehouseOrderModal";
import SelectActions from "@/views/components/SelectActions";
import WarehouseDetailModal from "./component/WarehouseDetailModal";
import ForceCompletionModal from "./component/ForceCompletionModal";
import WarehouseOrderSetModal from "./component/WarehouseOrderSetModal";
import SetIncomingWarehouseModal from "./component/SetIncomingWarehouseModal";
import useColumns from "./cloumns";
import { getCurrentUser } from "@/utils/authority";
import { ReconciliationTwoTone } from "@ant-design/icons";
import { getProductinboundorderList, setProductinboundorderEntry, getWarehouseList } from "./service";
import { hiprintTipsModal } from "@/utils/utils.jsx";
const GoodsWarehouseOrder = () => {
	const [visible, setVisible] = useState("");
	const warehouseList = useRef();
	const [printParams, setPrintParams] = useState({});
	const [printType, setPrintType] = useState({});
	const [selectedWarehouse, setSelectedWarehouse] = useState(null);
	const [filteredArray, setFilteredArray] = useState([]);
	const [recordItem, setRecordItem] = useState({}); //每行数据
	const tableRequest = getProductinboundorderList;
	const { defaultColumns } = useColumns({
		handleDetailVisible,
		selectedWarehouse,
		warehouseList,
		handleWarehouseChange
	});
	const [columns, setColumns] = useState(defaultColumns);
	const [record, setRecord] = useState("");

	const beforeQuerySearch = ({ API_DATA }) => {
		const KEYS = ["documentNos", "inboundOrderNos"];
		// 逗号分割转换数组
		KEYS.forEach(key => {
			API_DATA[key] = API_DATA[key]?.split(",");
		});
		getWarehouseColumns();
		if (API_DATA.endTime && !API_DATA.timeType) {
			API_DATA.timeType = 1;
		}
		if (API_DATA.warehouseName && API_DATA.warehouseName.length > 0) {
			API_DATA.warehouseName = API_DATA.warehouseName.map(item => item.label);
		}

		return API_DATA;
	};
	const tableKey = "GoodsWarehouseOrder312";
	const { selectedKeys, selectedRows, fetchList, dataSource, form, query, pagination, updateDataSource, searchSimpleTableProps } =
		useTableConfig({
			tableKey,
			rowKey: "id",
			columns: columns,
			tableRequest,
			autoFetch: true,
			hasPagination: true,
			hasQuickSearch: true,
			beforeQuerySearch,
			resetSourceData: false,
			hasColsSetting: true,
			hasToggleSearchForm: true,
			columnResize: true
		});
	async function getWarehouseColumns() {
		const res = await getWarehouseList();
		const { success, data } = res;

		if (success) {
			const list = [
				{ label: "发货仓", options: [], kind: 1 },
				{ label: "次品仓", options: [], kind: 2 },
				{ label: "销退仓", options: [], kind: 3 }
			];
			(data || []).forEach(item => {
				const ind = list.findIndex(e => e.kind === item.kind);
				list[ind].options.push({
					...item,
					value: item.id,
					label: item.warehouseName
				});
			});
			warehouseList.current = list;
		}
		const filteredArray = columns.filter((item, index) => {
			return columns;
		});
		setColumns(filteredArray);
	}
	const commonHandleClick = (status, record) => {
		// 新增入库单
		if (status == "AddWarehouseOrderModal") {
			return setVisible(status);
		}
		// 入库单设置
		if (status == "WarehouseOrderSetModal") {
			return setVisible(status);
		}
		// 打印入库标签
		if (status == "print") {
			setPrintType(2);
			if (!hiprint.hiwebSocket.opened) {
				return hiprintTipsModal();
			}
			let filteredArray = selectedRows.filter(
				item => item.status == "wait-inboundOrder" || item.status == "partial-inboundOrder"
			);
			if (!filteredArray.length) {
				return message.info("没有可操作的数据，请重新勾选");
			}
			setPrintParams(selectedRows);
			setFilteredArray(filteredArray);
			setVisible(status);
		} else if (status == "ForceCompletionModal") {
			// 强制完成
			const filteredArray = selectedRows.filter(
				item => item.status === "partial-inboundOrder" && ['manual-creation', 'return-warehousing'].includes(item.sourceType)
			);
			if (filteredArray.length > 0) {
				setVisible(status);
				setFilteredArray(filteredArray);
			} else {
				return message.info("没有可操作的数据，请重新勾选");
			}
		} else if (status == "SetIncomingWarehouseModal") {
			const filteredArray = selectedRows.filter(
				item => item.status === "wait-inboundOrder" || item.status === "partial-inboundOrder"
			);
			if (filteredArray.length > 0) {
				setVisible(status);
				setFilteredArray(filteredArray);
			} else {
				return message.info("没有可操作的数据，请重新勾选");
			}
		} else if (status == "Cancellation") {
			// 作废
			const filteredArray = selectedRows.filter(
				item => item.status === "wait-inboundOrder" && ['manual-creation', 'return-warehousing'].includes(item.sourceType)
			);
			if (filteredArray.length > 0) {
				setVisible(status);
				setFilteredArray(filteredArray);
			} else {
				return message.info("没有可操作的数据，请重新勾选");
			}
			// 作废
		} else {
			if (selectedRows.length) {
				const filteredArray = selectedRows.filter(item => item.payStatus !== 1);
				if (filteredArray.length > 0) {
					setVisible(status);
				} else {
					return message.info("没有可操作的数据，请重新勾选");
				}
			} else {
				Modal.info({ centered: true, content: "请选择操作数据" });
			}
		}
	};

	async function handleWarehouseChange(value, record, type) {
		if (type === "select") {
			setSelectedWarehouse(value.value);
		} else {
			setSelectedWarehouse(value.value);

			let list = [];
			list.push(record.inboundOrderNo);
			const { success } = await setProductinboundorderEntry({
				inboundOrderNoList: list,
				warehouseType: value.title,
				warehouseId: value.value,
				warehouseName: value.label
			});
			if (success) {
				message.success("修改成功");
				fetchList();
			}
		}
	}
	async function handleDetailVisible(record) {
		setRecord(record);
		setVisible("OrderDetailModal");
	}
	const CheckWarehouseProps = {
		visible,
		query,
		fetchList,
		checkedRows: selectedRows,
		dataSource,
		warehouseList,
		filteredArray,
		record,
		checkedIds: selectedKeys,
		handleOk() {
			updateTableList(selectedRows);
		},
		handleCancel() {
			setVisible("");
		}
	};

	const PrintModalProps = {
		visible: visible,
		printType,
		dataSource,
		recordItem,
		filteredArray,
		printParams,
		selectedKeys,
		handleCancel() {
			setVisible("");
			setRecordItem({});
		},
		handleOk(val) {
			setVisible("");
			setRecordItem({});
		}
	};

	const LeftBtns = (
		<Space>
			<SelectActions name="新建入库单" onClick={() => commonHandleClick("AddWarehouseOrderModal")} />
			<SelectActions name="强制完成" onClick={() => commonHandleClick("ForceCompletionModal")} />
			<SelectActions name="作废" onClick={() => commonHandleClick("Cancellation")} />
			<SelectActions name="设置入仓仓库" onClick={() => commonHandleClick("SetIncomingWarehouseModal")} />
			<SelectActions name="打印入库标签" onClick={() => commonHandleClick("print")} />
		</Space>
	);
	const rightBtns = (
		<Space>
			<SelectActions type="text" onClick={() => commonHandleClick("WarehouseOrderSetModal")}>
				<ReconciliationTwoTone className="main-color" />
				入库设置
			</SelectActions>
		</Space>
	);
	return (
		<>
			{columns && (
				<SearchCheckboxTable
					key={tableKey}
					leftBtns={LeftBtns}
					rightBtns={rightBtns}
					mounted={false}
					{...searchSimpleTableProps}
				/>
			)}
			{visible == "AddWarehouseOrderModal" && <AddWarehouseOrderModal {...CheckWarehouseProps} />}
			{visible == "ForceCompletionModal" && <ForceCompletionModal {...CheckWarehouseProps} />}
			{(visible == "ForceCompletionModal" || visible == "Cancellation") && <ForceCompletionModal {...CheckWarehouseProps} />}
			{visible == "WarehouseOrderSetModal" && <WarehouseOrderSetModal {...CheckWarehouseProps} />}
			{visible == "OrderDetailModal" && <WarehouseDetailModal {...CheckWarehouseProps} />}
			{visible == "SetIncomingWarehouseModal" && <SetIncomingWarehouseModal {...CheckWarehouseProps} />}
			{visible == "print" && <PrintModal {...PrintModalProps} />}
		</>
	);
};

export default React.memo(GoodsWarehouseOrder, () => {
	return true;
});
